const cheerio = require('cheerio')
const axios = require('axios')

let pageNum = 0;

function getPageNum() {
    let httpUrl = "https://www.qidian.com/free/all?orderId=&vip=hidden&style=1&pageSize=20&siteid=1&pubflag=0&hiddenField=1&page=1"
    return axios.get(httpUrl).then(res => {
        let $ = cheerio.load(res.data)
        $('.page-box .pagination .lbf-pagination-item-list li a').each((index, ele) => {
            if (index == 5) {
                pageNum = $(ele).text();
                for (var i = 1; i <= pageNum; i++) {
                    getPage(i)
                }
            }
        })
    })
}

function getPage(page) {
    let httpUrl = "https://www.qidian.com/free/all?orderId=&vip=hidden&style=1&pageSize=40&siteid=1&pubflag=0&hiddenField=1&page=" + page
    return axios.get(httpUrl).then(
        res => {
            let $ = cheerio.load(res.data)
            $('.free-container #free-channel-wrap .free-work .main-content-wrap .all-book-list ul>li .book-mid-info h4 a').each((index, ele) => {
                let href = $(ele).attr('href')
                href = `https:${href}`
                bookInfo(href)
            })
        }
    )
}

function bookInfo(href) {
    return axios.get(href).then(
        res => {
            let $ = cheerio.load(res.data);
            let bookName = "";
            let bookImgUrl = "";
            let author = "";
            let type = "";
            let remark = "";
            $('.book-detail-wrap .book-information #bookImg>img').each((index, ele) => {
                bookImgUrl = `https:${$(ele).attr("src")}`
            })
            $('.book-detail-wrap .book-information .book-info h1 em').each((index, ele) => {
                bookName = $(ele).text()
            })
            $('.book-detail-wrap .book-information .book-info span a').each((index, ele) => {
                author = $(ele).text()
            })
            $('.book-detail-wrap .book-information .book-info .tag span').each((index, ele) => {
                type += $(ele).text()
            })
            $('.book-detail-wrap .book-information .book-info .tag a').each((index, ele) => {
                type += $(ele).text()
            })
            $('.book-detail-wrap .book-information .book-info .intro').each((index, ele) => {
                remark = $(ele).text()
            })
            let Arr = [bookName, bookImgUrl, author, type, remark]
            let strSql = "insert into asyadminbook (bookName, bookImgUrl, author, type, remark) values (?,?,?,?,?)"
            con.query(strSql, Arr, (err, data) => {
                if (err) {
                    console.log(err)
                } else {
                    console.log(data)
                }
            })
        })
}

getPageNum()